package cn.wowjoy.pda.android_pharmacy.ui.activity.staticH.take;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;

import cn.wowjoy.pda.android_pharmacy.R;
import cn.wowjoy.pda.android_pharmacy.common.core.BaseActivity;
import cn.wowjoy.pda.android_pharmacy.common.utils.Contants;
import cn.wowjoy.pda.android_pharmacy.common.utils.NetWorkUtils;
import cn.wowjoy.pda.android_pharmacy.common.utils.PreferenceManager;
import cn.wowjoy.pda.android_pharmacy.common.widget.CreateDialog;
import cn.wowjoy.pda.android_pharmacy.common.widget.MDialog;
import cn.wowjoy.pda.android_pharmacy.common.widget.MyToast;
import cn.wowjoy.pda.android_pharmacy.databinding.ActivityStaticTakeProgressBinding;
import cn.wowjoy.pda.android_pharmacy.model.xmlEntity.inHospitalPatientInfo.InHospitalPatientBeen;
import cn.wowjoy.pda.android_pharmacy.mvvm.presenter.staticH.StaticTakeProgressPresenter;
import cn.wowjoy.pda.android_pharmacy.mvvm.vm.staticH.StaticTakeProgressViewModel;

public class StaticTakeProgressActivity extends BaseActivity<ActivityStaticTakeProgressBinding, StaticTakeProgressViewModel, StaticTakeProgressPresenter> implements StaticTakeProgressPresenter.OnSubmitResult {

    private MDialog failSubmit;
    private MDialog mMDialog;
    private float countAlready = 0;
    private InHospitalPatientBeen remove;
    //当次药单 种类总数量
    private float TOTAL_NUM = Integer.parseInt(PreferenceManager.getInstance().getStaticTakeProgressTotal());
    //设置缓存柜是否成功
    private boolean isSetCache = false;
    //是否取完药
    private boolean isGetAll = false;


    //PDA扫码广播
    private ScanReceiver mScanReceiver;
    private IntentFilter intentFilter;

    @Override
    protected void init(Bundle savedInstanceState) {
        binding.setViweModel(viewModel);
        binding.setPresenter(presenter);
        binding.medicineIdScanGet.setText(presenter.DJJLID);
//        presenter.registeOnScanResultListener(this);
        presenter.registeOnSubmitResultListener(this);
        binding.scanGetTitle.titleTextTv.setText("扫码取药");
        binding.scanGetTitle.titleBackLl.setVisibility(View.VISIBLE);
        binding.scanGetTitle.titleBackLl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                if (viewModel.mMoveBaens.size() != 0) {
                    viewModel.mMoveBaens.add(0, remove);
                }
                if (TOTAL_NUM - countAlready == 1) {
                    viewModel.mMoveBaens.add(0, remove);
                }
                intent.putExtra("currently", viewModel.mMoveBaens);
                setResult(Contants.REQUEST_BACK_CODE, intent);
                finish();
            }
        });
        binding.scanGetTitle.titleBackTv.setText("取药单详情");
        binding.btDoorTakeProgressSureSuccess.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //TODO:整个单子完成，跳转到Index     还要判断是否是2人同时操作同一个订单 先后完成？？
//                presenter.update("1", PreferenceManager.getInstance().getLUserId());
                if(NetWorkUtils.isWifi(StaticTakeProgressActivity.this)){
                    presenter.quey("99",presenter.DJJLID);
                }else{
                    CreateDialog.failDialog3(StaticTakeProgressActivity.this,"错误","当前网络不可用，请检查你的网络设置");
                }
            }
        });

        //TODO:进度条更新   分子什么时候加一
        ifBack();
        updateFirstUI();
        //TODO:PDA扫码广播的接收跳转
        mScanReceiver = new ScanReceiver();
        intentFilter = new IntentFilter();
        intentFilter.addAction(Contants.WOW_NEW_ADD);

//        binding.imgv123.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//
//                Intent intent = new Intent(StaticTakeProgressActivity.this, StaticTakeProgressDetailActivity.class);
//                intent.putExtra("topRemove", remove);
//                startActivityForResult(intent, Contants.REQUEST_CODE);
//
//            }
//        });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case Contants.REQUEST_CODE:
                switch (resultCode) {
                    case Contants.RESULT_SUCCESS_CODE:
                        //进度+1 ，界面展现集合中的第一个
                        if (countAlready < TOTAL_NUM) {
                            countAlready++;
                        }

                        if (countAlready == TOTAL_NUM) {
                            //扫码完成
//                            binding.scanGetTitle.titleTextTv.setText("放入缓存柜");
                            binding.llScanGetStart.setVisibility(View.GONE);
                            binding.rlScanGetEnd.setVisibility(View.VISIBLE);
                            binding.rlVoice.setVisibility(View.VISIBLE);
                            binding.scanGetTitle.titleBackLl.setVisibility(View.GONE);
                            binding.tvProgressScanGet.setText((int) countAlready + "/" + (int) TOTAL_NUM);
                            binding.progressScanGet.setProgress(100);
                        }
                        updateFirstUI();
                        break;
                    case Contants.RESULT_FAIL_CODE:
                        //back键 界面不做更新

                        break;
                }
                break;
        }
    }

    private void ifBack() {
        //说明是0/12 Back回去的
//        if(viewModel.FirstTotal.size() == TOTAL_NUM){
//            binding.tvProgressScanGet.setText(countAlready+"/"+ TOTAL_NUM);
//        }
        //说明是中途取到2/12 回去的
        if (viewModel.FirstTotal.size() < TOTAL_NUM) {
            countAlready = TOTAL_NUM - viewModel.FirstTotal.size();
        }
    }

    //TODO:界面药品信息的更新   库位和处方号的更新？？
    private void updateFirstUI() {
        binding.tvProgressScanGet.setText((int) countAlready + "/" + (int) TOTAL_NUM);
        if (viewModel.mMoveBaens.size() > 0) {
            remove = viewModel.remove();
            if(null != remove.getKFWZMC() && !"".equals(remove.getKFWZMC())){
                if( null != remove.getKFWZMC() && remove.getKFWZMC().length()>6){
                    binding.locatorScanGet.setText(remove.getKFWZMC().substring(0,7));  //库位
                } else {
                    binding.locatorScanGet.setText(remove.getKFWZMC());  //库位
                }
            }
            if(null != remove.getSFGWPB() && !"".equals(remove.getSFGWPB())){
                if(Integer.parseInt(remove.getSFGWPB()) == 1){
                    binding.medicineNameScanGet.setTextColor(getResources().getColor(R.color.red));
                }else {
                    binding.medicineNameScanGet.setTextColor(getResources().getColor(R.color.text_undanger));
                }
            }
            binding.medicineNameScanGet.setText(remove.getZZYPMC() + "  " + remove.getZZYPGG());
            binding.numScanGet.setText(remove.getCFYPSL());
            binding.placeScanGet.setText(remove.getYPCDMC());
            binding.progressScanGet.setProgress((int) ((countAlready / TOTAL_NUM) * 100));
        }
        if (countAlready == TOTAL_NUM) {
            //8/8 BACK回去的
            binding.llScanGetStart.setVisibility(View.GONE);
            binding.rlScanGetEnd.setVisibility(View.VISIBLE);
            binding.rlVoice.setVisibility(View.VISIBLE);
            binding.scanGetTitle.titleBackLl.setVisibility(View.GONE);
            binding.progressScanGet.setProgress(100);
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver(mScanReceiver, intentFilter);
    }

    @Override
    protected void onStop() {
        super.onStop();
        unregisterReceiver(mScanReceiver);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        CreateDialog.dismiss(StaticTakeProgressActivity.this);
        if (null != mMDialog) {
            mMDialog.cancel();
        }
        if (null != failSubmit) {
            failSubmit.cancel();
        }
    }

    @Override
    public void onBackPressed() {
        //药单未完成  BACK键返回  每次要把当前展示的加到集合中
        Intent intent = new Intent();
        if (viewModel.mMoveBaens.size() != 0) {
            viewModel.mMoveBaens.add(0, remove);
        }
        if (TOTAL_NUM - countAlready == 1) {
            viewModel.mMoveBaens.add(0, remove);
        }
        intent.putExtra("currently", viewModel.mMoveBaens);
        setResult(Contants.REQUEST_BACK_CODE, intent);
        super.onBackPressed();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_static_take_progress;
    }

    @Override
    protected Class<StaticTakeProgressPresenter> getPresenterClass() {
        return StaticTakeProgressPresenter.class;
    }

    @Override
    protected Class<StaticTakeProgressViewModel> getViewModelClass() {
        return StaticTakeProgressViewModel.class;
    }

    //更新整个单子成功
    @Override
    public void submitSuccess() {
        new MyToast(StaticTakeProgressActivity.this).showinfo("取药成功");
        startActivity(new Intent(StaticTakeProgressActivity.this, StaticTakeIndexActivity.class));
        finish();
    }

    //更新整个单子失败
    @Override
    public void submitFail(String errMsg) {
        //单子更新异常    ??
        failSubmit = CreateDialog.failSubmit(StaticTakeProgressActivity.this, "取药失败", "该取药单已有其他人取药完成，请重新确认", new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(StaticTakeProgressActivity.this, StaticTakeIndexActivity.class));
                finish();
            }
        });
    }

    //TODO:接收PDA扫码广播，准备跳转
    class ScanReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            switch (intent.getAction()) {
                case Contants.WOW_NEW_ADD:
                    String stringExtra = intent.getStringExtra(Contants.WOW_NEW_KEY);
//                    new MyToast(StaticTakeProgressActivity.this).showinfo("扫到的是: "+stringExtra);
//                    Log.e("onReceive1: ", remove.toString());
                    if (binding.rlScanGetEnd.getVisibility() == View.GONE) {
                         if (stringExtra.length() == 20) {
                            //监管码 前7位
                            if (presenter.confimYPJGBM(stringExtra.substring(0, 7))) {
                                Intent intent2 = new Intent(StaticTakeProgressActivity.this, StaticTakeProgressDetailActivity.class);
                                intent2.putExtra("topRemove", remove);
                                startActivityForResult(intent2, Contants.REQUEST_CODE);
                            } else {
                                mMDialog = CreateDialog.failDialog(StaticTakeProgressActivity.this);
                            }
                            break;
                        } else if (stringExtra.length() == 7) {
                            //库位码
                            if (presenter.confimKFWZMC(stringExtra)) {
                                Intent intent2 = new Intent(StaticTakeProgressActivity.this, StaticTakeProgressDetailActivity.class);
                                intent2.putExtra("topRemove", remove);
                                startActivityForResult(intent2, Contants.REQUEST_CODE);
                            } else {
                                mMDialog = CreateDialog.failDialog(StaticTakeProgressActivity.this);
                            }
                            break;
                        } else {
                                 //药品码
                                 //扫码后进行对比，true跳转，false弹框提示
                                 if (presenter.confimYPSPBM(stringExtra)) {
                                     Intent intent2 = new Intent(StaticTakeProgressActivity.this, StaticTakeProgressDetailActivity.class);
                                     intent2.putExtra("topRemove", remove);
                                     startActivityForResult(intent2, Contants.REQUEST_CODE);
                                 } else {
                                     mMDialog = CreateDialog.failDialog(StaticTakeProgressActivity.this);
                                 }
                                 break;
                        }
                    }
            }
        }
    }
}
